//
//  DindingPhoneViewController.m
//  WGFGlobalHouse
//
//  Created by waiguofang on 15/4/15.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//  绑定手机

#define scrollviewHeiht (UIScreenHeight + 10)

#import "BindingPhoneViewController.h"
#import "CoreGraphics/CoreGraphics.h"
#import "LoginDataMange.h"
#import "UserModal.h"
#import "MBProgressHUD+MJ.h"
#import "UIView+circular.h"

#import "config.h"
#import "StringTool.h"

@interface BindingPhoneViewController ()<UIAlertViewDelegate,UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *mainView;


@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;


@property (weak, nonatomic) IBOutlet UIButton *redBtn;
@property (strong, nonatomic) LoginDataMange *dataMange;
- (IBAction)clickRedBtn:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;//验证码

@end

@implementation BindingPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    self.dataMange = [[LoginDataMange alloc]init];
    [self initView];
    
}

-(void)initView
{
    [self.titleView setMianTitle:@"激活账号"];
    self.titleView.doneBtn.hidden = YES;
    self.phoneTextField.delegate = self;
    self.codeTextField.delegate = self;
       [self.redBtn viewToCircular];
    
    
}

#pragma mark 点击获取验证码
- (IBAction)clickGetCodeBtn:(id)sender {
    [self handlePhone];
}


#pragma mark 判断手机号码的格式，发送验证码请求
-(void)handlePhone
{
    if ([self checkPhone]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            
            ResulteMod *mod = [self.dataMange captchaWithMobile:self.phoneTextField.text];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (mod.resltState == ResultFail)
                {
                    [MBProgressHUD showError:mod.resultTip];
                }else if(mod.resltState == ResultNetError)
                {
                    [MBProgressHUD showError:@"网络错误"];
                }else
                {
                    [MBProgressHUD showSuccess:@"验证码已发送，请注意查收"];
                }
            });
        });
    }
}

#pragma mark 校验手机号和验证码
-(BOOL)checkPhoneAndCode
{
    if ([StringTool isBlankString:self.phoneTextField.text]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return NO;
    }else if (![self validateMobile:self.phoneTextField.text])
    {
        [MBProgressHUD showError:@"请输入正确的手机号"];
        return NO;
    }else if ([StringTool isBlankString:self.codeTextField.text])
    {
        [MBProgressHUD showError:@"请输入验证码"];
        return NO;
    }
    return YES;
    
}

#pragma mark 校验手机号
-(BOOL)checkPhone
{
    if ([StringTool isBlankString:self.phoneTextField.text]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return NO;
    }else if (![self validateMobile:self.phoneTextField.text])
    {
        [MBProgressHUD showError:@"请输入正确的手机号"];
        return NO;
    }
    return YES;
}

- (IBAction)clickRedBtn:(UIButton *)sender {
    if ([self checkPhoneAndCode]) {
        
        [self updata];
    }
}

#pragma mark 提交数据
-(void)updata
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    //去掉手机号前面的空格
    __weak typeof(self)bself = self;
    NSString *codeStr = [self.codeTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *mod =   [bself.dataMange activitymobileWithMobile:[UserModal shareUserModel].mobile WithCaptcha:codeStr WithConsumerId:[UserModal shareUserModel].userId];
        
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:bself.view animated:YES];
                    if(mod.resltState == ResultFail)
                    {
                        [MBProgressHUD showError:mod.resultTip];
                    }else if (mod.resltState == ResultNetError)
                    {
                        [MBProgressHUD showError:@"网络错误"];
                    }else
                    {
                        [MBProgressHUD showSuccess:@"账号已激活!"];
                    }                    

        });
    });
}
#pragma mark textField的代理
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    
    CGRect dd =  [textField.superview convertRect:textField.frame toView:self.mainView];
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-[UserModal shareUserModel].keyboardHeight-tvbotY- 64;
    
    if (mid<0) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.view.frame;
        buf.origin.y = up ? mid : 0;
        [self.mainView setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}



-(void)viewRest{
    
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.mainView.frame;
    buf.origin.y =  0;
    [self.mainView setFrame:buf];
    
    [UIView commitAnimations];
}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self animateTextField:textField up:false];
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}

#pragma mark 验证码倒计时
-(void)Countdown
{
    __block NSInteger timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeout <=0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
            
        }else
        {
            timeout--;
        }
    });
    dispatch_resume(timer);
}


@end
